import { useState } from 'react';
import { Button, Dropdown, Modal, Form, Input, message } from 'antd';
import { FileExcelOutlined, FileWordOutlined, FilePdfOutlined, DownOutlined } from '@ant-design/icons';
import style from './index.module.less';
import { useMemo } from 'react';
import { throttle } from '@/utils/debounceThrottle';

export const ExportDoc = ({ 
  selectedDocs = [], 
  onExport,
  onExportPdf,
  selectedCount = 0,
  loading = false
}) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();

  const handleExport = async () => {
    if (selectedCount === 0) {
      message.warning('请先选择要导出的文档');
      return;
    }
    
    if (onExport) {
      await onExport();
    }
  };

  const handleExportPdf = async () => {
    if (selectedCount === 0) {
      message.warning('请先选择要导出的文档');
      return;
    }
    
    if (onExportPdf) {
      await onExportPdf();
    }
  };
  
  const throttledExport = useMemo(() => throttle(handleExport, 1000), [handleExport]);
  const throttledExportPdf = useMemo(() => throttle(handleExportPdf, 1000), [handleExportPdf]);

  const items = [
    { key: 'word', label: '导出为Word文档', icon: <FileWordOutlined />, onClick: throttledExport },
    { key: 'pdf', label: '导出为PDF文档', icon: <FilePdfOutlined />, onClick: throttledExportPdf },
  ];


  return (
    <>
      <div className={style.box}>
        <Dropdown
          menu={{ items }}
          placement="bottomLeft"
          trigger={['click']}
        >
          <Button 
            type="primary" 
            loading={loading}
            disabled={selectedCount === 0}
          >
            <span className={style.firIcon}>
              <FileWordOutlined />
            </span>
            <span>
              导出 {selectedCount > 0 && `(${selectedCount})`}
            </span>
            <span className={style.secIcon}>
              <DownOutlined />
            </span>
          </Button>
        </Dropdown>
      </div>

      <Modal
        title="导出Excel"
        open={isModalVisible}
        onOk={() => {
          form.validateFields().then((values) => {
            setIsModalVisible(false);
            form.resetFields();
          });
        }}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
        }}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="fileName"
            label="文件名"
            rules={[{ required: true, message: '请输入文件名' }]}
          >
            <Input placeholder="请输入文件名" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};